package com.tdzh.maimaiti.util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by hisou on 2016/5/5.
 */
public class JSONBuilder {

    public static JSONObject setJsonBuilder(Set<?> interest)  {
        JSONObject jsonObject = new JSONObject();
        int count = 0;
        for(Object s : interest){
            try {

                jsonObject.put("value" + count, s.toString());
                count++;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return jsonObject;
    }

    public static List<Map<String, String>> resolveJSONArray(String jsonArray){

        List<Map<String, String>> list = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(jsonArray);
            for (int i = 0; i < array.length(); i++) {
                JSONObject itemObject = array.getJSONObject(i);
                Map itemMap = new HashMap();

                JSONArray names = itemObject.names();
                if (names != null) {
                    for (int j = 0; j < names.length(); j++) {
                        String name = names.getString(j);
                        String value = itemObject.getString(name);
                        itemMap.put(name, value);
                    }
                }
                list.add(itemMap);
            }
        } catch (JSONException e) {

        }
        return list;
    }
}
